<?php
include_once "functions.php";

	function setup() {	
		if ( isset( $_POST ) ) {
			$response = array ( "error"		=>	"",
									"success"	=>	"" 
						);
			if ( isset($_POST['dbname']) and isset($_POST['dbusername']) and isset($_POST['dbpassword']) ) {		
				# Check if db exists.
				$dbname = ( $_POST['dbname'] == "" ) ? "notesrack" : $_POST['dbname'];
				$dbhost = ( $_POST['dbhost'] == "" ) ? "localhost" : $_POST['dbhost'];
				$dbport = ( $_POST['dbport'] == "" ) ? "3306" : $_POST['dbport'];
				$dbusername = ( $_POST['dbusername'] == "" ) ? "" : $_POST['dbusername'];
				$dbpassword = ( $_POST['dbpassword'] == "" ) ? "" : $_POST['dbpassword'];
							
				$dsn = sprintf( "mysql:dbname=%s;host=%s;port=%s", $dbname, $dbhost, $dbport );
		
				try {
					$dbh = new PDO( $dsn, $_POST['dbusername'], $_POST['dbpassword'] );
					$stmnt = $dbh->prepare("SELECT count(*) AS found_tables FROM information_schema.tables WHERE table_schema = :dbname");
					
					$stmnt->bindParam(":dbname", $dbname);
					$results = $stmnt->execute();
					
					$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
					$dbh->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); 
			
					$results = $stmnt->fetchAll();

					$found_tables = $results[0]['found_tables'];
								
					if ( $found_tables > 0 ) {
						$response["error"] .= "Database is not empty. Please provide an empty database.";
						return $response;
					}				
				} catch (PDOException $e) {
					$response["error"] .= "<b>Connection to database failed!<br>";
					$response["error"] .= "Veryify that the database exists already, and is empty.<br>";
					$response["error"] .= "And the credentails are correct and the user is authorized.</b><br>";
					return $response;
				}
				
				// Meaning, the connection was succesful and we have an empty schema.
				$create_schema = array( "CONFIGURATION" => "
											CREATE TABLE configuration (
											  param varchar(56) NOT NULL,
											  value varchar(45) DEFAULT NULL,
											  PRIMARY KEY (param),
											  UNIQUE KEY param_UNIQUE (param)
											)",

										"NOTES" => "CREATE TABLE notes (
										  note_id int(11) NOT NULL AUTO_INCREMENT,
										  note_title text,
										  note_content mediumtext,
										  note_author int(11) DEFAULT NULL,
										  note_privacy varchar(10) DEFAULT 'public',
										  note_tags tinytext,
										  PRIMARY KEY (note_id),
										  UNIQUE KEY note_id_UNIQUE (note_id)
										)",
										
										"USERS" 	=> 	"CREATE TABLE users (
										  user_name varchar(126) NOT NULL,
										  user_id smallint(6) NOT NULL AUTO_INCREMENT,
										  passphrase varchar(126) NOT NULL,
										  user_email varchar(256) NOT NULL,
										  user_state varchar(9) DEFAULT NULL,
										  auth_reset_key varchar(126) DEFAULT NULL,
										  registered_at datetime DEFAULT NULL,
										  auth_key_birth datetime DEFAULT NULL,
										  PRIMARY KEY (user_name,user_id),
										  UNIQUE KEY user_id_UNIQUE (user_id),
										  UNIQUE KEY user_name_UNIQUE (user_name)
									)",
									"PASSPHRASE_SALT"	=>	"INSERT INTO CONFIGURATION VALUES( 'passphrase_salt', '" . crypt(mt_rand()) . "' )",
									"AUTH_TYPE"	=>	"INSERT INTO CONFIGURATION VALUES( 'auth_type', 'simple' )"
								);
						
				foreach ( $create_schema as $table=>$query ) {
					try {
						$dbh->query($create_schema[$table]);
					} catch( PDOException $e ) {
						$response["error"] .= sprintf( "Could not create table %s<br>", $create_schema[$table] );
					}
				}
				if ( ! empty ( $response["error"] ) ) {
					return $response;
				}
				if ( ! $fh = fopen("config.php", "w") ) {
					$response["error"] .= "Could not open config file for writing. Make sure that your webserver's scripts dir is writable";
					return $response;
				}
				$data = sprintf ("<?php
# Generated file. Edit this file only if you know what you are doing!
define('DBHOST', '%s');
define('DBPORT', '%s');
define('USER', '%s');
define('PASSWORD', '%s');
define('DBNAME', '%s');
?>", $dbhost, $dbport, $dbusername, $dbpassword, $dbname );
				fwrite($fh, $data);	# write stuff.
				fclose ($fh);
				
				$response["success"] .= sprintf('Setup complete. You may now add notes by logging in from: <a href="%s">%s</a>', get_url_to("notes.php"), get_url_to("notes.php") );					
				return $response;
			}
		} else {
			$response["error"] .= "You should fill in the mandatory fields.";
			return $response;
		}			
	}

	$response = setup();
?>

<!doctype html>
<html>
<head>
<link href="css/notesrack.css" rel="stylesheet" type="text/css">  

</head>

<body id="install">
  <h1>Setup a notesrack</h1>
  <?php 
	if ( file_exists("config.php") and empty( $_POST ) ) {
		echo "<b>An existing installation found! You may continue anyway.</b>";
	}
  ?>
  <form name="install" method="POST" action="#">
	  <table>
		<tr>
			<td>
			Database name:
			</td>
			<td>
			<input type="text" autocomplete="off"  name="dbname" placeholder="mysql db name" value="<?php if ( isset($_POST['dbname']) ) { echo $_POST['dbname']; }?>"/>
			</td>
		</tr>
		
		<tr>
			<td>
			Database host:
			</td>
			<td>
			<input type="text" autocomplete="off"  name="dbhost" placeholder="Defaults to localhost" value="<?php if ( isset($_POST['dbhost']) ) { echo $_POST['dbhost']; }?>" />
			</td>
		</tr>

		<tr>
			<td>
			Database port:
			</td>
			<td>
			<input type="text" autocomplete="off"  name="dbport" placeholder="Defaults to port 3306" value="<?php if ( isset($_POST['dbport']) ) { echo $_POST['dbport']; }?>" />
			</td>
		</tr>

		<tr>
			<td>
			Database username:
			</td>
			<td>
			<input type="text" autocomplete="off"  name="dbusername" placeholder="Database username" value="<?php if ( isset($_POST['dbusername']) ) { echo $_POST['dbusername']; }?>" />
			</td>
		</tr>

		<tr>
			<td>
			Database password:
			</td>
			<td>
			<input type="password" name="dbpassword" placeholder="Database user password" value="<?php if ( isset($_POST['dbpassword']) ) { echo $_POST['dbpassword']; }?>" />
			</td>
		</tr>

		<tr>
			<td>
			<input type="submit" name="create_rack" value="Submit"/>
			<input type="button" name="cancel" value="Cancel"/>
			</td>
		</tr>
	  </table>
  </form>
  
  <div id="setup_outcome">  
	<?php 
		if ( !empty( $response["error"] ) ) {
			echo $response["error"];
		}
		
		if ( !empty( $response["success"] ) ) {
			echo $response["success"];
		}		
	?>
  </div>
</body>
</html>
